#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
创建真实的HAI实例
"""

import os
import sys
import json
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

# 加载环境变量
from dotenv import load_dotenv
load_dotenv()

def create_real_hai_instance():
    """创建真实的HAI实例"""
    print("🏗️ 创建真实的HAI实例")
    print("=" * 50)
    
    try:
        from tencentcloud.common import credential
        from tencentcloud.hai.v20230812 import hai_client, models
        from tencentcloud.common.profile.client_profile import ClientProfile
        from tencentcloud.common.profile.http_profile import HttpProfile
        
        # 创建凭证
        cred = credential.Credential(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY')
        )
        
        # 创建客户端
        profile = ClientProfile()
        profile.httpProfile = HttpProfile()
        profile.httpProfile.endpoint = "hai.tencentcloudapi.com"
        
        client = hai_client.HaiClient(cred, "ap-beijing", profile)
        
        print("✅ HAI客户端创建成功")
        
        # 创建实例请求
        req = models.RunInstancesRequest()
        
        # 设置必需参数
        req.ApplicationId = "app-oefac6i2"  # 使用北京的真实应用ID
        req.InstanceName = "beijing-hai-instance"
        req.InstanceCount = 1
        req.BundleType = "HAI_T4"  # 尝试使用T4 BundleType
        
        # 设置系统盘
        system_disk = models.SystemDisk()
        system_disk.DiskType = "CLOUD_PREMIUM"
        system_disk.DiskSize = 50
        req.SystemDisk = system_disk
        
        print(f"📋 实例创建参数:")
        print(f"  ApplicationId: {req.ApplicationId}")
        print(f"  InstanceName: {req.InstanceName}")
        print(f"  InstanceCount: {req.InstanceCount}")
        print(f"  BundleType: {req.BundleType}")
        print(f"  SystemDisk.Type: {system_disk.DiskType}")
        print(f"  SystemDisk.Size: {system_disk.DiskSize}GB")
        
        # 执行创建实例
        print(f"\n🚀 开始创建真实HAI实例...")
        resp = client.RunInstances(req)
        
        print(f"✅ 实例创建成功!")
        print(f"请求ID: {resp.RequestId}")
        
        if hasattr(resp, 'InstanceIdSet') and resp.InstanceIdSet:
            instance_ids = resp.InstanceIdSet
            print(f"实例ID列表: {instance_ids}")
            
            for instance_id in instance_ids:
                print(f"\n📊 实例详情:")
                print(f"  实例ID: {instance_id}")
                print(f"  应用ID: {req.ApplicationId}")
                print(f"  实例名称: {req.InstanceName}")
                print(f"  地域: ap-beijing")
                
                # 查询实例状态
                try:
                    status_req = models.DescribeInstancesRequest()
                    status_req.InstanceIds = [instance_id]
                    status_resp = client.DescribeInstances(status_req)
                    
                    if status_resp.InstanceSet:
                        instance_info = status_resp.InstanceSet[0]
                        print(f"  实例状态: {instance_info.InstanceState}")
                        print(f"  创建时间: {instance_info.CreatedTime}")
                        
                except Exception as e:
                    print(f"  状态查询失败: {e}")
            
            return instance_ids[0] if instance_ids else None
        else:
            print("❌ 未返回实例ID")
            return None
            
    except Exception as e:
        print(f"❌ 创建实例失败: {e}")
        import traceback
        traceback.print_exc()
        return None

def check_instance_status(instance_id):
    """检查实例状态"""
    print(f"\n🔍 检查实例 {instance_id} 状态...")
    
    try:
        from tencentcloud.common import credential
        from tencentcloud.hai.v20230812 import hai_client, models
        from tencentcloud.common.profile.client_profile import ClientProfile
        from tencentcloud.common.profile.http_profile import HttpProfile
        
        # 创建凭证
        cred = credential.Credential(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY')
        )
        
        # 创建客户端
        profile = ClientProfile()
        profile.httpProfile = HttpProfile()
        profile.httpProfile.endpoint = "hai.tencentcloudapi.com"
        
        client = hai_client.HaiClient(cred, "ap-beijing", profile)
        
        # 查询实例
        req = models.DescribeInstancesRequest()
        req.InstanceIds = [instance_id]
        resp = client.DescribeInstances(req)
        
        if resp.InstanceSet:
            instance = resp.InstanceSet[0]
            print(f"✅ 实例状态查询成功:")
            print(f"  实例ID: {instance.InstanceId}")
            print(f"  实例名称: {instance.InstanceName}")
            print(f"  实例状态: {instance.InstanceState}")
            print(f"  应用ID: {instance.ApplicationId}")
            print(f"  创建时间: {instance.CreatedTime}")
            
            return True
        else:
            print("❌ 实例不存在")
            return False
            
    except Exception as e:
        print(f"❌ 状态查询失败: {e}")
        return False

def main():
    """主函数"""
    print("🚀 创建真实HAI实例")
    print("=" * 60)
    
    # 检查环境变量
    secret_id = os.getenv('TENCENT_SECRET_ID')
    secret_key = os.getenv('TENCENT_SECRET_KEY')
    
    if not secret_id or not secret_key:
        print("❌ 环境变量未配置")
        return False
    
    print(f"Secret ID: {secret_id[:10]}...")
    print(f"Secret Key: {secret_key[:10]}...")
    print(f"目标地域: ap-beijing")
    print(f"目标应用: app-oefac6i2")
    
    # 创建真实实例
    instance_id = create_real_hai_instance()
    
    if instance_id:
        # 检查实例状态
        check_instance_status(instance_id)
        
        print(f"\n🎉 真实HAI实例创建完成！")
        print(f"\n📋 总结:")
        print(f"✅ 实例ID: {instance_id}")
        print(f"✅ 应用ID: app-oefac6i2")
        print(f"✅ 地域: ap-beijing")
        print(f"✅ 实例名称: beijing-hai-instance")
        print(f"✅ 系统盘: 50GB CLOUD_PREMIUM")
        
        print(f"\n🔗 后续操作:")
        print(f"- 可以在腾讯云控制台查看实例详情")
        print(f"- 可以通过API管理实例状态")
        print(f"- 可以部署应用和任务")
        
        return True
    else:
        print(f"\n❌ 真实实例创建失败")
        print(f"\n💡 可能的原因:")
        print(f"- 权限不足")
        print(f"- 配额限制")
        print(f"- 参数错误")
        print(f"- 服务不可用")
        
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
